package com.be.beadmin.service.task;

import com.be.beadmin.service.event.Event;
import com.be.beadmin.service.event.EventListener;
import com.be.beadmin.service.event.ShutdownEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *  @Description 任务基类
 */
public abstract class BaseTask implements Task, EventListener {
	
	/** 任务名称 */
	private String name;
	
	/** 当前时间 */
	private long currentTime;
	
	/** 耗时（秒） */
	private long elapsedTime;
	
	/** 当前线程句柄 */
	private Thread currentThread;
	
	/** 线程运行标志 */
	private boolean running = false;
	
	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	public BaseTask(String name) {
		this.name = name;
	}
	
	/**
	 * @see Runnable#run()
	 */
	@Override
	public void run() {
		this.currentThread = Thread.currentThread();
		this.running = true;
		logger.info("任务[ {} ]", this.name);
		doTask();
	}
	
	/**
	 * @description 执行任务
	 */
	public abstract void doTask();

	@Override
	public void onEvent(Event event) {
		if (!(event instanceof ShutdownEvent)) {
			return;
		}
		logger.warn("监听到进程退出事件，[ {} ]任务即将退出......", getName());
		this.running = false;
		this.currentThread.interrupt();
	}

	/**
	 * 判断当前进程是否该继续执行
	 * @return true-是；false-否
	 */
	protected boolean isRunning() {
		return (!this.currentThread.isInterrupted() && this.running);
	}

	/**
	 * 任务开始前执行
	 */
	@Override
	public void beforeTask() {
		currentTime = System.currentTimeMillis();
	}

	/**
	 * 任务结束后执行
	 */
	@Override
	public void afterTask() {
		elapsedTime = (System.currentTimeMillis() - currentTime) / 1000;
	}
	
	/**
	 * @param name {@link #name}
	 */
	public void setName(String name) {
		this.name = name;
	}
	
	/**
	 * 获得任务名称
	 */
	@Override
	public String getName() {
		return name;
	}

	/**
	 * 获得任务执行时间（秒）
	 */
	@Override
	public long getElapsedTime() {
		return elapsedTime;
	}

}
